<template>
  <a-modal :visible="visible" :title="title" width="760px" @cancel="handleCancel">
    <DynamicForm :config="dyConfig" :questions="dyQuestions" ref="dyRef"></DynamicForm>
    <template #footer>
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" :loading="state.loading" @click="handleOk">{{ okText }}</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { computed, getCurrentInstance, onBeforeUnmount, reactive, ref } from 'vue';
import { DynamicForm } from '@/components/public-template';
import indexService from './addPlan.service';
import { Api, planSave } from '@/config/api/archivesCollectPlan';
import { message } from 'ant-design-vue';
import { RESETTABLE, SELECTSERVE } from '@/mixins/subject/subject-types';
import { filter } from 'rxjs/operators';
import dictionary from '@/filters/dictionary';
import { formInfoStore } from '@/store/modules/form';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  showType: {
    type: String
  },
  data: {
    type: Object
  }
});
const emit = defineEmits(['update:visible', 'update:showType', 'handleEdit']);
const state = reactive({
  deptList: [],
  menList: [],
  loading: false
});
const TITLE = {
  ADD: '添加计划',
  VIEW: '计划详情',
  EDIT: '编辑计划'
};
const OK_TEXT = {
  ADD: '确定',
  VIEW: '编辑',
  EDIT: '确定'
};
const title = computed(() => TITLE[props.showType]);
const okText = computed(() => OK_TEXT[props.showType]);
const dyRef = ref(null);
const dyConfig: any = reactive({
  name: 'propsConfig',
  id: props.data?.id,
  queryUrl: `${Api.planGet}/${props.data?.id}`,
  labelCol: 12,
  isView: props.showType === 'ADD' ? false : true,
  wrapperCol: 24,
  grid: 12,
  layout: 'vertical',
  cancelSave: true,
  beforeWithMethod: (data) => {
    if (!data) return;
    if (props.showType == 'VIEW') {
      if (data.dept) data.dept = data.dept.map((item) => item.executorName).join('；');
      if (data.men) data.men = data.men.map((item) => item.executorName).join('；');
    } else if (props.showType == 'EDIT') {
      if (data.dept) data.dept = data.dept.map((item) => item.executorId);
      if (data.men) data.men = data.men.map((item) => item.executorId);
    }
    return data;
  }
});

const formStore = formInfoStore();
formStore.setQuestions(reactive(props.showType === 'VIEW' ? indexService.getQuestions() : indexService.getQuestions()));
const dyQuestions = reactive(formStore.getQuestions);
// 监听table
const { proxy }: any = getCurrentInstance();
const subscribeSub = proxy.$NotificationFormSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item: any) => {
    if (item.key === SELECTSERVE) {
      if (item.value.key == 'dept') {
        state.deptList = item.value.data;
      } else if (item.value.key == 'men') {
        state.menList = item.value.data;
      }
    }
  });
function handleOk() {
  if (props.showType == 'ADD' || props.showType == 'EDIT') {
    dyRef.value.onFinish(
      (data) => {
        // 预警天数不能大于执行频率天数
        const days = toFequencyDays(data.frequencyNum, data.frequencyUnit);
        if (data.warningPeriod > days) return message.warning('预警天数不能大于执行频率天数');
        // 部门数据
        if (data.dept.length > 0) data.dept = data.dept.map((item) => getDeptFromId(item, props.showType !== 'EDIT' ? state.deptList : dyQuestions[2].options));
        // 执行人数据
        if (data.men.length > 0) data.men = data.men.map((item) => getMenFromId(item, props.showType !== 'EDIT' ? state.menList : dyQuestions[3].options));
        state.loading = true;
        planSave(data)
          .then((result) => {
            if (result.success) {
              message.success(`${props.showType == 'ADD' ? '添加' : '修改'}成功`);
              proxy.$NotificationFormSub.pushParams({ key: RESETTABLE, value: { name: 'planTable' } });
              emit('update:visible', false);
            }
            state.loading = false;
          })
          .catch((err) => {
            state.loading = false;
            return Promise.reject(err);
          });
      },
      false,
      true
    );
  } else if (props.showType == 'VIEW') {
    dyConfig.isView = false;
    !dyQuestions[2].value ? (dyQuestions[2].value = []) : null;
    !dyQuestions[3].value ? (dyQuestions[3].value = []) : null;
    emit('handleEdit', props.data);
  } else {
    emit('update:visible', false);
  }
}
// 根据id获取部门数据
function getDeptFromId(id, list) {
  if (!list.length) return;
  function reData(relist: any[]) {
    for (let i = 0; i < relist.length; i++) {
      if (id == relist[i].id) {
        return {
          executorId: id,
          executorName: relist[i].name
        };
      } else if (relist[i].childOrg && relist[i].childOrg.length > 0) {
        const result = reData(relist[i].childOrg);
        if (result) return result;
      }
    }
  }
  return reData(list);
}
// 根据id获取执行人数据
function getMenFromId(id, list) {
  if (!list.length) return;
  const data = list.find((item) => item.id == id) || {};
  return {
    executorId: data.id,
    executorName: data.nickName
  };
}
function handleCancel() {
  emit('update:visible', false);
}
// 执行频率转换成单次频率天数
function toFequencyDays(num, unit) {
  // unit 0=周 1=月 2=年
  switch (unit) {
    case 0:
      return num * 7;
    case 1:
      return num * 30;
    case 2:
      return num * 365;
    default:
      break;
  }
}
onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  proxy.$NotificationPubSub.clearParams();
});
</script>

<style lang="less" scoped>
:deep(.ant-picker) {
  width: 100%;
}
</style>
